<template>
  <el-card shadow="hover">
    <el-dialog v-model="dialogOrderAttach" title="上传合同附件" @close="close">
      <el-upload
        v-model:file-list="fileList"
        :multiple="true"
        action="https://api.sanjianke.com/common/Upload/upload?file=OrderAttach&type=image"
        list-type="picture-card"
      >
        <!-- :disabled="!isUpOrderAttach" -->
        <el-icon><Plus /></el-icon>
        <template #file="{ file }">
          <div style="width: 100%; height: 100%">
            <div
              v-if="isImage(file) == true"
              style="position: relative; cursor: pointer"
            >
              <!-- <div style="position: absolute;z-index:100;right:0px;top:0px;cursor: pointer;">
                <el-icon :size="20" color="#FF0000" @click="handleRemove(file)"><CircleCloseFilled /></el-icon>
              </div> -->
              <el-image
                :src="file.url"
                fit="cover"
                style="width: 170px; height: 170px"
              />
            </div>
            <div
              v-else
              style="
                position: relative;
                height: 100%;
                width: 100%;
                text-align: center;
                cursor: pointer;
              "
              @click="handlePictureCardPreview(file)"
            >
              <!-- <div style="position: absolute;z-index:100;right:0px;top:0px;cursor: pointer;">
                <el-icon :size="20" color="#FF0000" @click="handleRemove(file)"><CircleCloseFilled /></el-icon>
              </div> -->
              <span style="font-size: 20px; line-height: 140px">
                {{ isImage(file) }} 文件
              </span>
            </div>
            <span class="el-upload-list__item-actions">
              <span
                class="el-upload-list__item-preview"
                @click="handlePictureCardPreview(file)"
              >
                <el-icon><zoom-in /></el-icon>
              </span>
              <span
                v-if="OrderInfo.OrderState == 1"
                class="el-upload-list__item-delete"
                @click="handleRemove(file)"
              >
                <el-icon><Delete /></el-icon>
              </span>
            </span>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="handleSaveOrderAttach">
            确认上传
            <!-- v-if="isUpOrderAttach"  -->
          </el-button>
        </div>
      </template>
      <!-- <el-dialog v-model="dialogVisible" top="3vh">
        <img
          w-full
          :src="dialogImageUrl"
          alt="Preview Image"
          style="width: 100%"
        />
      </el-dialog> -->
    </el-dialog>
    <el-image-viewer
      v-if="dialogVisible"
      :url-list="[dialogImageUrl]"
      @close="closeViewer"
    />
    <el-descriptions class="margin-top" title="合同信息" :column="3" border>
      <template #extra>
        <el-select
          v-model="OrderInfo.querenYeji"
          style="width: 150px; float: left"
        >
          <el-option label="请选择" :value="0" />
          <el-option label="核算业绩" :value="1" />
          <el-option label="不核算业绩" :value="-1" />
        </el-select>
        <el-input
          v-if="OrderInfo.querenYeji == -1"
          v-model="OrderInfo.noQuerenReason"
          placeholder="请输入不核算业绩的原因"
          style="width: 200px; float: left; margin-left: 10px"
        />
        <el-button
          v-if="actstaffpostid == 9 || actstaffpostid == 42"
          :type="OrderInfo.isQuerenYeji ? 'success' : 'danger'"
          style="float: left; margin-left: 10px"
          @click="querenYeji(OrderInfo.OrderID)"
        >
          确认业绩核算
        </el-button>
        <el-button
          v-else
          :type="OrderInfo.isQuerenYeji ? 'success' : 'info'"
          style="float: left; margin-left: 10px"
        >
          <span v-if="OrderInfo.querenYeji == 1">核算业绩</span>
          <span v-else-if="OrderInfo.querenYeji == -1">不核算业绩</span>
          <span v-else>待确认业绩</span>
        </el-button>
        <el-button :type="green ? 'success' : 'danger'" @click="isDrawer">
          查看基本信息
        </el-button>
      </template>
    </el-descriptions>
    <el-form ref="formRef" :model="OrderInfo" :rules="rules">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="客户名称：">
            <el-text color="#000" style="font-size: 16px; font-weight: 500">
              {{ OrderInfo.CustomerAllName }}
            </el-text>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="客户ID：">
            <el-text color="#000" style="font-size: 16px; font-weight: 500">
              {{ OrderInfo.CustomerID }}
            </el-text>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="商机业务类：" style="display: flex">
            <el-text color="#000">{{ OrderInfo.BusinessOrderName }}</el-text>
            <el-button
              v-if="
                actstaffpostid == 2 ||
                actstaffpostid == 6 ||
                actstaffpostid == 9 ||
                actstaffpostid == 42
              "
              type="primary"
              size="small"
              plain
              style="margin-left: 10px"
              @click="showBusinessPath(OrderInfo.OrderID)"
            >
              商机流转过程
            </el-button>
            <el-button
              v-if="
                actstaffpostid == 2 ||
                actstaffpostid == 6 ||
                actstaffpostid == 9 ||
                actstaffpostid == 42
              "
              type="success"
              size="small"
              plain
              @click="showBusinessRecord(OrderInfo.OrderID)"
            >
              商机跟进小记
            </el-button>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="合同ID：">
            <el-text color="#000" style="font-size: 16px; font-weight: 500">
              {{ OrderInfo.OrderID }}
            </el-text>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="商机类型：">
            <el-text
              v-if="OrderInfo.BusinessOrderType === 0"
              style="color: green"
            >
              新签商机
            </el-text>
            <el-text
              v-if="OrderInfo.BusinessOrderType === 2"
              style="color: #ff6600"
            >
              回签商机
            </el-text>
            <el-text
              v-if="OrderInfo.BusinessOrderType === 9"
              style="color: #ff0000"
            >
              老系统合同
            </el-text>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="3">
          <el-form-item label="签单来源" prop="SignOrderIn">
            <el-input v-model="OrderInfo.SignOrderIn" :disabled="disabled" />
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="签单方式" prop="SignOrderType">
            <el-input v-model="OrderInfo.SignOrderType" :disabled="disabled" />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="跟进时长" prop="TrackTimeLength">
            <nobr>
              <el-input
                v-model="OrderInfo.TrackTimeLength"
                :disabled="disabled"
                style="width: 100px"
              />
              天
            </nobr>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="上门次数" prop="VisitCount">
            <nobr>
              <el-input
                v-model="OrderInfo.VisitCount"
                :disabled="disabled"
                style="width: 100px"
              />
              次
            </nobr>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="是否是捆绑单" prop="isOldOrder" required>
            <el-select v-model="OrderInfo.isOldOrder" :disabled="disabled">
              <!-- <el-option label="请选择" :value="-1" /> -->
              <el-option label="否" :value="0" />
              <el-option label="是" :value="1" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="捆绑单核算单量" prop="OldOrderCount">
            <el-input
              v-model="OrderInfo.OldOrderCount"
              type="number"
              :disabled="disabled"
              style="width: 110px"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="合同编号" prop="OrderCode" required>
            <el-space>
              <el-input
                v-if="modOrderCode && OrderFlowState < 4"
                v-model="OrderInfo.OrderCode"
                style="width: 260px"
              />
              <el-input
                v-else
                v-model="OrderInfo.OrderCode"
                :disabled="disabled"
                style="width: 260px"
              />
              <div v-if="OrderFlowState > 1 && OrderFlowState < 4">
                <el-button
                  v-if="modOrderCode"
                  type="primary"
                  :icon="Edit"
                  circle
                  style="float: right"
                  @click="modOrderCodeBtn(0)"
                />
                <el-button
                  v-else
                  type="success"
                  :icon="Check"
                  circle
                  style="float: right"
                  @click="modOrderCodeBtn(1)"
                />
              </div>
            </el-space>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="签约日期" prop="SignOrderDate" required>
            <el-date-picker
              v-model="OrderInfo.SignOrderDate"
              :disabled-date="disabledDate"
              :disabled="disabled"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合同属性" prop="OrderType" required>
            <el-select v-model="OrderInfo.OrderType" :disabled="disabled">
              <!-- <el-option label="请选择合同属性" :value="0" /> -->
              <el-option
                v-for="(item, index) in orderTypeOption"
                :key="index"
                :label="item.OrderTypeName"
                :value="item.OrderTypeID"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="签单人：" prop="SaleStaffName">
            <span style="color: #ff0000">{{ OrderInfo.SaleStaffName }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="5">
          <el-form-item label="总合同额" prop="OrderTotalMoney" required>
            <!-- <el-input-number
              v-model="OrderInfo.OrderTotalMoney"
              precision="2"
              :step="100"
              :disabled="disabled"
              style="width: 170px"
            /> -->
            <el-input
              v-model="OrderInfo.OrderTotalMoney"
              type="number"
              :disabled="disabled"
              style="width: 110px"
            />
            <el-text style="padding-left: 10px">元</el-text>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="收款方式" prop="OrderFenqi" required>
            <!-- <el-checkbox v-model="OrderInfo.OrderFenqi">分期收款</el-checkbox> -->
            <el-select v-model="OrderInfo.OrderFenqi" :disabled="disabled">
              <!-- <el-option label="请选择收款方式" :value="-2" /> -->
              <el-option label="全额收款" :value="0" />
              <el-option label="分期收款" :value="1" />
              <el-option label="不收款" :value="-1" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="注：不含备付金金额" />
        </el-col>
        <el-col :span="5">
          <el-form-item label="备付金金额" prop="ReserveMoney" required>
            <!-- <el-input-number
              v-model="OrderInfo.ReserveMoney"
              precision="2"
              :step="100"
              :disabled="disabled"
            /> -->
            <el-input
              v-model="OrderInfo.ReserveMoney"
              type="number"
              :disabled="disabled"
              style="width: 110px"
            />
            <el-text style="padding-left: 10px">元</el-text>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="注：用于抵扣销量佣金" />
        </el-col>
      </el-row>
      <el-row
        :gutter="24"
        style="border-top: 1px solid #f0f0f0; padding-top: 20px"
      >
        <el-col :span="16">
          <el-form-item label="备注">
            <el-input v-model="OrderInfo.OrderMemo" :disabled="disabled" />
          </el-form-item>
        </el-col>
        <el-col :span="8" style="text-align: right">
          <el-button
            v-if="OrderFlowState === 1"
            type="primary"
            @click="saveContract"
          >
            保存合同信息
          </el-button>
          <el-button
            v-if="fileList.length === 0"
            type="danger"
            @click="uploadOrderAttachFile(true)"
          >
            上传合同/店铺名称及证照信息截图附件
          </el-button>
          <el-button
            v-else
            type="success"
            @click="uploadOrderAttachFile(false)"
          >
            上传合同/店铺名称及证照信息截图附件
          </el-button>
        </el-col>
      </el-row>
    </el-form>
  </el-card>
  <business-path ref="BusinessPathRef" />
  <business-record ref="BusinessRecordRef" />
</template>

<script>
  import { getBusinessClassSelect } from '@/api/common'
  import {
    saveOrderInfo,
    saveOrderAttach,
    saveQuerenYeji,
  } from '@/api/businessOrder'
  import BusinessPath from '@/views/components/BusinessPath'
  import BusinessRecord from '@/views/components/BusinessRecord'
  import { Check, Edit, Search } from '@element-plus/icons-vue'

  export default defineComponent({
    name: 'OrderInfo',
    components: { BusinessPath, BusinessRecord },
    emits: ['fetch-data', 'drawer'],
    setup(props, { emit }) {
      const $baseConfirm = inject('$baseConfirm')
      const $baseMessage = inject('$baseMessage')

      const state = reactive({
        green: false,
        formRef: null,
        BusinessPathRef: null,
        BusinessRecordRef: null,
        OrderFlowState: 1,
        disabled: false,
        modOrderCode: 0,
        OrderInfo: {
          // OrderType: 0,
          // isOldOrder: -1,
          OldOrderCount: 0,
          // OrderFenqi: -2
        },
        rules: {
          SignOrderIn: [
            { required: true, trigger: 'blur', message: '请添写签单来源' },
          ],
          SignOrderType: [
            { required: true, trigger: 'blur', message: '请添写签单方式' },
          ],
          TrackTimeLength: [
            { required: true, trigger: 'blur', message: '请添写跟进时长' },
          ],
          VisitCount: [
            { required: true, trigger: 'blur', message: '请添写跟进次数' },
          ],
          isOldOrder: [
            {
              required: true,
              trigger: 'blur',
              message: '请选择是否是捆绑单',
            },
          ],
          OldOrderCount: [
            {
              required: true,
              trigger: 'blur',
              message: '请添写老客户订单核算单量',
            },
          ],
          OrderCode: [
            { required: true, trigger: 'blur', message: '请添写合同编号' },
          ],
          SignOrderDate: [
            { required: true, trigger: 'blur', message: '请添写签约日期' },
          ],
          OrderType: [
            { required: true, trigger: 'blur', message: '请选择合同属性' },
          ],
          OrderTotalMoney: [
            { required: true, trigger: 'blur', message: '请添写合同金额' },
          ],
          OrderFenqi: [
            { required: true, trigger: 'blur', message: '请选择收款方式' },
          ],
          ReserveMoney: [
            { required: true, trigger: 'blur', message: '请添写备付金额' },
          ],
        },
        title: '',
        dialogFormVisible: false,
        orderTypeOption: [],
        BusinessClassOptions: [],
        dialogOrderAttach: false,
        fileList: [],
        OrderAttachForm: {},
        dialogImageUrl: '',
        dialogVisible: false,
        isUpOrderAttach: false,
        actstaffpostid: 0,
      })
      const modOrderCodeBtn = (t) => {
        state.modOrderCode = t
        if (!t) {
          saveContract()
        }
      }
      const showBusinessPath = (businessid) => {
        state.BusinessPathRef.showEdit(businessid)
      }
      const showBusinessRecord = (businessid) => {
        state.BusinessRecordRef.showEdit(businessid)
      }
      const disabledDate = (time) => {
        return time.getTime() > Date.now() // 8.64e7 毫秒数代表一天
      }

      const uploadOrderAttachFile = (n) => {
        state.isUpOrderAttach = n
        state.dialogOrderAttach = true
      }

      const handlePictureCardPreview = (uploadFile) => {
        console.log('uploadFile', uploadFile)
        // 判断是否是临时地址
        if (uploadFile.raw) {
          const isType = uploadFile.raw.type.split('/')[0]
          if (isType == 'image') {
            state.dialogImageUrl = uploadFile.url
            state.dialogVisible = true
          } else {
            window.open(uploadFile.url, '_blank')
          }
        } else {
          if (
            splitLastDot(uploadFile.url) == 'png' ||
            splitLastDot(uploadFile.url) == 'jpg' ||
            splitLastDot(uploadFile.url) == 'jpge'
          ) {
            state.dialogImageUrl = uploadFile.url
            state.dialogVisible = true
          } else {
            window.open(uploadFile.url, '_blank')
          }
        }
      }

      const changeOrderCode = () => {
        console.log('changeOrderCode', state.OrderInfo.OrderCode)
      }

      const handleRemove = (row) => {
        const index = state.fileList.findIndex((fileItem) => {
          console.log(fileItem.url, row.url, '123')
          return fileItem.url === row.url
        })
        state.fileList.splice(index, 1)
      }
      const isDrawer = () => {
        emit('drawer')
      }
      const closeViewer = () => {
        state.dialogImageUrl = ''
        state.dialogVisible = false
      }
      const querenYeji = (OrderID) => {
        if (
          state.OrderInfo.querenYeji == -1 &&
          !state.OrderInfo.noQuerenReason
        ) {
          $baseMessage(
            '请输入不核算业绩的原因',
            'warning',
            'vab-hey-message-warning'
          )
        } else {
          $baseConfirm('你确定要操作业绩核算吗？', null, async () => {
            const { msg } = await saveQuerenYeji({
              OrderID: OrderID,
              querenYeji: state.OrderInfo.querenYeji,
              noQuerenReason: state.OrderInfo.noQuerenReason,
            })
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            emit('fetch-data')
          })
        }

        // } else {
        //   $baseMessage('业绩核算已确认', 'success', 'vab-hey-message-success')
        // }
      }
      const handleSaveOrderAttach = async () => {
        console.log('fileList', state.fileList)
        const fileList = []

        state.fileList.forEach((item) => {
          if (item.response) {
            fileList.push({
              // name: item.name,
              url: item.response.data.url,
            })
          } else {
            fileList.push({
              // name: item.name,
              url: item.url,
            })
          }
        })
        state.OrderAttachForm.OrderAttachFile = fileList

        state.OrderAttachForm.OrderID = state.OrderInfo.OrderID

        if (fileList.length == 0) {
          ElMessage({
            message: '请先上传附件',
            type: 'warning',
          })
          return
        }
        const { msg } = await saveOrderAttach(state.OrderAttachForm)
        $baseMessage(msg, 'success', 'vab-hey-message-success')
        emit('fetch-data')
        state.dialogOrderAttach = false
      }
      // 是否是图片
      const isImage = (row) => {
        console.log(row, '搞不懂')

        if (row.raw) {
          // 临时地址
          const isType = row.raw.type.split('/')[0]
          const isTypeName = row.name.split('.')[1]
          if (isType == 'image') {
            return true
          } else {
            return isTypeName
          }
        } else {
          // 线上地址
          if (
            splitLastDot(row.url) == 'png' ||
            splitLastDot(row.url) == 'jpg' ||
            splitLastDot(row.url) == 'jpge'
          ) {
            return true
          } else {
            return splitLastDot(row.url)
          }
        }
      }
      // 反转字符串
      const splitLastDot = (msg) => {
        // 首先反转字符串
        const reversedStr = msg.split('').reverse().join('')
        // 使用split切割第一个点
        const parts = reversedStr.split('.')[0]
        // 结果反转并返回
        return parts.split('').reverse().join('')
      }
      const showOrder = (info, BusinessClass, green) => {
        state.green = green
        console.log(info, BusinessClass, '123')
        state.OrderFlowState = Math.abs(info.OrderFlowState)
        if (state.OrderFlowState !== 1) state.disabled = true
        console.log('state.OrderFlowState', state.OrderFlowState)
        state.OrderInfo = Object.assign({}, info)
        state.OrderInfo.isQuerenYeji = info.querenYeji
        state.fileList = JSON.parse(info.OrderAttachFile)
        console.log('fileList', state.fileList)
      }

      const saveContract = async () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            if (state.OrderInfo.OrderType == 0) {
              state.OrderInfo.OrderType = ''
              return false
            }
            if (state.OrderInfo.isOldOrder == -1) {
              state.OrderInfo.isOldOrder = ''
              return false
            }
            if (state.OrderInfo.OrderFenqi == -2) {
              state.OrderInfo.OrderFenqi = ''
              return false
            }
            const { msg } = await saveOrderInfo(state.OrderInfo)
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            emit('fetch-data')
          }
        })
      }

      const fetchData = async () => {
        state.listLoading = true
        const {
          data: { BusinessClassOptions, OrderTypeOption },
        } = await getBusinessClassSelect()
        state.BusinessClassOptions = BusinessClassOptions
        state.orderTypeOption = OrderTypeOption
        state.listLoading = false
      }

      onMounted(() => {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'))
        const actstaffpost = JSON.parse(userInfo.StaffPostID)
        state.actstaffpostid = actstaffpost[0][1]
        fetchData()
      })

      const close = () => {
        state.dialogOrderAttach = false

        state.fileList = JSON.parse(state.OrderInfo.OrderAttachFile)
      }

      return {
        ...toRefs(state),
        disabledDate,
        close,
        showOrder,
        isImage,
        saveContract,
        uploadOrderAttachFile,
        handleSaveOrderAttach,
        handlePictureCardPreview,
        handleRemove,
        splitLastDot,
        isDrawer,
        showBusinessPath,
        showBusinessRecord,
        querenYeji,
        changeOrderCode,
        modOrderCodeBtn,
        closeViewer,
        Check,
        Edit,
        Search,
      }
    },
  })
</script>
